<?php

namespace App\Http\Controllers;

use App\Jobs\NewsInsert;
use App\News;
use App\NewsImage;
use Illuminate\Auth\DatabaseUserProvider;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;

class TestController extends Controller
{
    public function index(Request $request)
    {
        Cache::flush();
        $time  = '2018-01';
        $table = 'news' . $time;
        $t     = date('t', strtotime($time)); // 获取天数
        $arr   = array_fill(1, $t, 'a'); // 填充数据
        // 创建表
//        if (Schema::hasTable($table) == false) {
//            News::CreateTable($table);
//        }
        foreach ($arr as $k => $v) {
            if ($k <= 9) {
                $d = $time . '-0' . $k;
            } else {
                $d = $time . '-' . $k;
            }
            // $d = $time . '-31';
            $key  = rand(99999999, 10000000) . rand(99999999, 10000000);
            $url  = 'https://news.zhibo8.cc/zuqiu/json/' . $d . '.htm?key=0.' . $key;
            $res  = file_get_contents($url); // 采集基本信息列表 $data['video_arr']
            $data = json_decode($res, true);
            foreach ($data['video_arr'] as $ke => $value) {
                NewsInsert::dispatch($value, 'news');
                // die;
                // static::news($value, 'news');
            }

        }
        return '完成';
    }


    /**
     * 下载远程图片保存到本地
     * @access public
     * @return array
     * @params string $url 远程图片地址
     * @params string $save_dir 需要保存的地址
     * @params string $filename 保存文件名
     * @since 1.0
     * @author
     */
    public static function download($url, $save_dir = './public/upload/loan/', $filename = '')
    {
        if (trim($save_dir) == '')
            $save_dir = './';
        if (trim($filename) == '') {//保存文件名
            $allowExt = array('.gif', '.jpg', '.jpeg', '.png', '.bmp');
            $ext      = strrchr($url, '.');
            if (!in_array($ext, $allowExt)) {
                return array('file_name' => '', 'save_path' => '', 'error' => 3);
            }
        }
        if (0 !== strrpos($save_dir, '/'))
            $save_dir .= '/';

        //创建保存目录
        if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true))
            return array('file_name' => '', 'save_path' => '', 'error' => 5);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        $file = curl_exec($ch);
        curl_close($ch);
        $filename = pathinfo($url, PATHINFO_BASENAME);
        $resource = fopen($save_dir . $filename, 'a');
        fwrite($resource, $file);
        fclose($resource);
        unset($file, $url);
        return array('file_name' => $filename, 'save_path' => $save_dir . $filename, 'error' => 0);
    }


    protected static function news($value, $table)
    {

        $url = 'https://news.zhibo8.cc';
        //  $value = $this->data;
        //  $table = $this->table;

        $name = $value['filename'];

        $res = (new News())->setTable($table)->where('index', '=', $name)->first();

        if (isset($value['label'])) {
            $insert['label'] = $value['label'];
        } else {
            $insert['label'] = $value['lable'];
        }

        if (is_null($res) === false || strpos($insert['label'], '足球') === false) { // 剔除没有足球标签,
            echo '已经添加';
        } else {
            // 准备数据
            $insert['title']       = $value['title'];
            $insert['from']        = $value['from_name'];
            $insert['update_time'] = strtotime($value['createtime']);
            $insert['index']       = $value['filename'];

            $str = file_get_contents($url . '/zuqiu/' . date('Y-m-d', $insert['update_time']) . '/' . $value['filename'] . '.htm');  // 采集主体新闻内容
// 描述
            preg_match_all('/<meta\s+name=[\"\']Description[\"\']\s+content=[\"\']([\S\s]*?)[\"\']\/?>/im', $str, $matchesD);
            if (!empty($matchesD[1])) {
                $insert['description'] = $matchesD[1][0];
            }
            // 文章详细内容
            preg_match_all('/<p.*?>(.*?)(?=<\/p>)/im', $str, $matches);
            $string = '';
            if (!empty($matches[0])) {
                foreach ($matches[0] as $v) {
                    $string .= $v;
                }
            }
            $id     = (new News())->setTable($table)->insertGetId($insert);
            $images = [];
            // 保存图片
            $ext = 'gif|jpg|jpeg|bmp|png';
            preg_match_all("/(src)=([\"|']?)([^ \"'>]+\.($ext))\\2/i", $string, $matches2);
            if (!empty($matches2[0])) {
                foreach ($matches2[0] as $k => $v) {
                    $num      = $k + 1;
                    $v        = str_replace('src=', '', $v);
                    $v        = str_replace('"', '', $v);
                    $images[] = [
                        'imgsrc'  => $v,
                        'news_id' => $id,
                        'status'  => 0,
                        'sort'    => $num
                    ];
                    // $all    = static::download($v, './public/images/' . date('Y-m-d', strtotime($value['createtime'])));
                    $string = str_replace($v, '{{imgsrc' . $num . '}}', $string);
                }
            }
            $insert['content'] = $string;
            (new News())->setTable($table)->where('id', '=', $id)->update(['content' => $string]);
            if (!empty($images)) {
                NewsImage::insert($images);
            }

        }
    }

    //队列长度监控
    public function queue()
    {
        $string = Cache::remember('zhuqiu', 5000, function () {
            return file_get_contents('https://www.zhibo8.cc/');
        });
//
//
        preg_match_all('/<li\s+label=.*足球.*?>(.*?)(?=<\/li>)/im', $string, $matches);
//
//        dump($matches);

        $this->test2();
        //$this->queue2();
    }


    public function queue2()
    {
        $parameters = ['host' => config('database.redis.default.host')];
        $options    = ['parameters' => ['password' => config('database.redis.default.password')]];
        $client     = new \Predis\Client($parameters, $options);
        $queues     = $client->keys('*queue*');
        $msg        = '';
        foreach ($queues as $queue) {
            $type = (string)$client->type($queue);
            $len  = 0;
            switch ($type) {
                case "zset":
                    //$len = $client->zcount($queue, 0, 10000);
                    break;
                case "list":
                    $len = $client->llen($queue);
                    break;
                default:
            }
            if (($queue == 'save_log_to_redis') && ($len > 1000)) {
                $msg .= "$msg\n队列 {$queue} 长度超过预警：$len";
            } else if ($len > 50) {
                $msg .= "$msg\n队列 {$queue} 长度超过预警：$len";
            }
        }

        //  dump($msg);
    }


    public function test2()
    {
        News::where('content', 'like', '%直播吧%')->chunkById(200, function ($res) {
            foreach ($res as $k => $v) {
                $des = str_replace('直播吧', '', $v->content);
                News::where('id', '=', $v->id)->update(['content' => $des]);
            }
            if (count($res) == 0) {
                return false;
            }
        });
    }


    public function git()
    {
//        $command = " D:";
//        system($command, $return_var);
//        dump($return_var);
//        $command = " cd /home/wwwroot/news_qingmi_site/";
//        system($command, $return_var);
//        dump($return_var);
//        $command = '&& sudo /usr/bin/git pull';
//        $command = ' cd /home/wwwroot/news_qingmi_site && sub git pull origin master';
//        exec($command, $output, $return_var);
//        dump($output);
//        dump($return_var);

        $command = 'cd /usr/share/nginx/html/zhuqiunews  && git pull origin master ';
        system($command, $output);
        dump($output);
        dump(3);

    }
}
